package com.M.lock;

import lombok.extern.slf4j.Slf4j;

/**
 * @author kanlei
 * @email freefree.me@qq.com
 * @since 2021/9/3
 */
@Slf4j
public abstract class AbstractLock implements Lock {
    @Override
    public void lock() throws Exception {
        if (tryLock()) {
            log.info("{} try acquire lock success.", Thread.currentThread().getName());
        } else {
            log.info("{} try acquire lock failure.", Thread.currentThread().getName());
            log.info("{} wait this lock .", Thread.currentThread().getName());
            waitLock();
            lock();
        }
    }

    /**
     * 等待释放锁 -> 阻塞的
     */
    protected abstract void waitLock() throws Exception;

    /**
     * try acquire lock
     *
     * @return whether acquire lock
     */
    protected abstract boolean tryLock() throws Exception;
}
